﻿#region File Header
/***********************************************************************
 * Copyright © 2013 Beals Software
 * All Rights Reserved
************************************************************************
Author: Donald Beals
Date: February 4th, 2013
Description: TODO: Write a description of this file here.
****************************** Change Log ******************************
02.04.13 - Created initial file. (dbeals)
***********************************************************************/
#endregion

#region Using Statements
using System;
using System.Linq;
using GameJolt.Async;
#endregion

namespace GameJolt.Requests
{
	/// <summary>
	/// 
	/// </summary>
	internal abstract class WebRequestBase<TResult> : AsyncRequestBase<TResult>
	{
		#region Variables
		private RequestParameterCollection parameters = new RequestParameterCollection();
		#endregion

		#region Properties
		public override string GameID
		{
			get
			{
				return GetParameterString("game_id");
			}
			set
			{
				Parameters["game_id"] = value;
			}
		}

		public string UrlBase
		{
			get;
			protected set;
		}

		public RequestParameterCollection Parameters
		{
			get
			{
				return parameters;
			}
		}
		#endregion

		#region Constructors
		public WebRequestBase(string gameID, string privateKey)
			: base(gameID, privateKey)
		{
		}
		#endregion

		#region Methods
		private static string AppendParameter(string url, string parameter)
		{
			return url + (url.Contains('?') ? "&" : "?") + parameter;
		}

		private static string AppendParameter(string url, string name, string value)
		{
			return AppendParameter(url, string.Format("{0}={1}", name, value));
		}

		protected string GetParameterString(string parameterName, string defaultValue = null)
		{
			if(Parameters.Contains(parameterName))
				return defaultValue;
			return (string)Parameters[parameterName];
		}

		protected virtual void UpdateParameters()
		{
		}

		protected string GetFullUrl()
		{
			UpdateParameters();
			var output = UrlBase;
			var parametersString = string.Join<RequestParameter>("&", Parameters.ToArray());

			if(!string.IsNullOrWhiteSpace(parametersString))
				output = AppendParameter(output, parametersString);

			var signature = RequestHelper.CreateSignature(output, PrivateKey);
			output = AppendParameter(output, "signature", signature);

			return Uri.EscapeUriString(output);
		}

		public override TResult Process(IAsyncResult result)
		{
			if(Logging.IsEnabled)
				Logging.LogInformation(GetFullUrl());
			return default(TResult);
		}
		#endregion
	}
}
